import { reactive, ref, nextTick } from "vue";
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';

export const loginProvider = () => {

  const { tm } = useI18n();
  const store = useStore();

  let loading = ref(false);
  let capsTooltip = ref(false);

  let passwordType = ref('password');

  const passwordRef = ref(null);
  const loginRef = ref(null);
  const userRef = ref(null);

  const loginForm = reactive({
    username: '',
    password: '',
    domainId: ''
  })
  const loginRules = reactive({
    username: [{ required: true, trigger: 'blur', message: tm('plm.login.usernameTip') }],
    password: [{ required: true, trigger: 'blur', message: tm('plm.login.pwdTip') }],
    domainId: []    
  })

  const checkCapslock = ({ shiftKey, key } = {}) => {
    if (key && key.length === 1) {
      if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
        capsTooltip = true;
      } else {
        capsTooltip = false;
      }
    }
    if (key === 'CapsLock' && capsTooltip === true) {
      capsTooltip = false;
    }
  }
  const showPwd = () => {
    if (passwordType === 'password') {
      passwordType = '';
    } else {
      passwordType = 'password';
    }
    nextTick(() => {
      passwordRef.value.focus();
    })
  }

  const login = () => {
    // console.log(loginRef);
    return new Promise((reslove, reject) => {
      if (loginForm.username == "admin" || loginForm.username == "Administrator") {
        loginRules.domainId = [];
      } else {
        loginRules.domainId = [{ required: true, trigger: 'blur', message: '域不能为空' }];
      }  
      loginRef.value.validate(async valid => {
        if (valid) {
          try {
            loading.value = true;
            const result = await store.dispatch('user/login', loginForm);
            console.log(result);
            reslove(result)
            
          } catch(err) {
            console.log(err);
            reject(err);
          } 
          finally {
            loading.value = false;
          }
        } else {
          reject(false);
          console.warn('error submit!!');
        }
      })



    })
    
  }

  return {
    loading,
    loginForm,
    loginRules,
    capsTooltip,
    userRef,
    loginRef,
    passwordRef,
    passwordType,
    checkCapslock,
    showPwd,
    login
  }

}









